package co.edu.poli.ficb.agl.automatable.gui;

import java.awt.Point;
import java.awt.Rectangle;
import java.awt.event.MouseEvent;
import java.awt.geom.Point2D;

import javax.swing.JOptionPane;

import co.edu.poli.ficb.agl.automatable.graph.Arista;
import co.edu.poli.ficb.agl.automatable.graph.GrafoAutomata2;
import co.edu.poli.ficb.agl.automatable.graph.Vertice;
import co.edu.poli.ficb.agl.automatable.modelo.automatas.Automata;
import edu.uci.ics.jung.algorithms.layout.GraphElementAccessor;
import edu.uci.ics.jung.algorithms.layout.Layout;
import edu.uci.ics.jung.visualization.Layer;
import edu.uci.ics.jung.visualization.VisualizationViewer;
import edu.uci.ics.jung.visualization.control.LabelEditingGraphMousePlugin;

/**
 * 
 * @author Diego
 * @version 0.1
 * @since 0.1
 *
 */
public class PA2LabelEditingGraphMousePlugin extends LabelEditingGraphMousePlugin<Vertice,Arista> {

	private GrafoAutomata2 grafo;
	
	public Automata automata;
	
	private PA2LabelConfiguration labelConfiguration;

	public PA2LabelEditingGraphMousePlugin(GrafoAutomata2 grafo,Automata automata,PA2LabelConfiguration labelConfiguration) {
		this.grafo = grafo;
		this.automata = automata;
		this.labelConfiguration = labelConfiguration;
	}

	@SuppressWarnings({ "unchecked", "rawtypes" })
	@Override
	public void mouseClicked(MouseEvent e) {

		if (e.getModifiers() == modifiers && e.getClickCount() == 2) {

			final VisualizationViewer<Vertice, Arista> vv = (VisualizationViewer) e.getSource();
			GraphElementAccessor<Vertice, Arista> pickSupport = vv.getPickSupport();
			if (pickSupport != null) {
				Layout<Vertice, Arista> layout = vv.getGraphLayout();
				Point2D p = e.getPoint();
				// take away the view transform
				Point2D ip = vv.getRenderContext().getMultiLayerTransformer().inverseTransform(Layer.VIEW, p);

				Vertice vertice = pickSupport.getVertex(layout, p.getX(),p.getY());
				
				if (vertice != null) {
					String nuevaEtiqueta = JOptionPane.showInputDialog("Nueva etiqueta para este estado");
					if (nuevaEtiqueta != null) {
						automata.cambiarEtiquetaEstado(vertice.getEtiqueta(), nuevaEtiqueta);
						vertice.setEtiqueta(nuevaEtiqueta);
						vv.repaint();
					}
					return;
				}

				final Arista arista = pickSupport.getEdge(layout,ip.getX(),ip.getY());
				if (arista != null) {
					Point punto = labelConfiguration.getPosition(arista);
					
					AristaTextField tf = new AristaTextField(arista, vv, grafo);
					vv.add(tf);
					
					// Pinta el JTextField sobre la etiqueta de la arista.
					tf.setBounds(new Rectangle(punto, tf.getPreferredSize()));
					
					vv.validate();
					tf.requestFocusInWindow();
					// TODO
					PA2EditingModalGraphMouse gm = (PA2EditingModalGraphMouse) vv.getGraphMouse();
					gm.setMode(MyMode.VIEWING);
				}
			}
			e.consume();
		}
	}
	
	
}